//@ts-nocheck
export async function createOptimizedImageRenderer(canvas: HTMLCanvasElement) {
    // 检查WebGPU支持
    if (!navigator.gpu) {
        throw new Error("WebGPU not supported")
    }

    // 请求适配器和设备

    const adapter = await navigator.gpu.requestAdapter({
        powerPreference: "high-performance", // 请求高性能GPU
    })

    if (!adapter) {
        throw new Error("No appropriate GPU adapter found")
    }

    // 请求具有缓存功能的设备
    const device = await adapter.requestDevice({
        requiredFeatures: [],
        requiredLimits: {
            maxStorageBufferBindingSize:
                adapter.limits.maxStorageBufferBindingSize,
            maxBufferSize: adapter.limits.maxBufferSize,
        },
    })

    // 配置Canvas上下文

    const context = canvas.getContext("webgpu")

    const format = navigator.gpu.getPreferredCanvasFormat()
    context.configure({
        device,
        format,
        alphaMode: "premultiplied",
        // 启用高性能配置
        usage:
            window.GPUTextureUsage.RENDER_ATTACHMENT |
            window.GPUTextureUsage.COPY_SRC,
    })

    // 创建着色器
    const shader = device.createShaderModule({
        code: `
      struct BaizeVertexShaderOutput {
        @builtin(position) position: vec4f,
        @location(0) texcoord: vec2f,
      };
  
      @vertex fn vs(
        @builtin(vertex_index) vertexIndex : u32
      ) -> BaizeVertexShaderOutput {
        let pos = array(
          // 1st triangle
          vec2f( -1.0,  -1.0),  // center
          vec2f( 1.0,  -1.0),  // right, center
          vec2f( -1.0,  1.0),  // center, top

          // 2st triangle
          vec2f( -1.0,  1.0),  // center, top
          vec2f( 1.0,  -1.0),  // right, center
          vec2f( 1.0,  1.0),  // right, top
        );

        var vsOutput: BaizeVertexShaderOutput;
        let xy = pos[vertexIndex];
        vsOutput.position = vec4f(xy * 2.0 - 1.0, 0.0, 1.0);
        vsOutput.texcoord = vec2f(xy.x, 1.0 - xy.y);
        return vsOutput;
      }

      @group(0) @binding(0) var ourSampler: sampler;
      @group(0) @binding(1) var ourTexture: texture_2d<f32>;

      @fragment fn fs(fsInput: BaizeVertexShaderOutput) -> @location(0) vec4f {
        return textureSample(ourTexture, ourSampler, fsInput.texcoord);
      }
      `,
    })

    // 创建纹理缓存映射
    const textureCache = new Map()
    // 创建渲染管线
    const pipeline = device.createRenderPipeline({
        layout: "auto",
        vertex: {
            module: shader,
        },
        fragment: {
            module: shader,
            targets: [{ format }],
        },
    })

    // 创建高质量采样器
    const sampler = device.createSampler({
        addressModeU: "clamp-to-edge",
        addressModeV: "clamp-to-edge",
        magFilter: "linear",
        minFilter: "linear",
        mipmapFilter: "linear",
        maxAnisotropy: 16, // 高质量纹理过滤
    })

    // 用于加载和缓存纹理的函数
    async function loadImageTexture(imageUrl) {
        // 检查缓存
        if (textureCache.has(imageUrl)) {
            return textureCache.get(imageUrl)
        }

        // 加载图像
        const img = new Image()
        img.crossOrigin = "anonymous"
        img.src = imageUrl
        await new Promise((resolve) => {
            img.onload = resolve
        })

        // 使用ImageBitmap进行高效处理
        const bitmap = await createImageBitmap(img, {
            colorSpaceConversion: "none", // 避免额外的颜色空间转换
            premultiplyAlpha: "premultiply", // 与alphaMode匹配
        })

        // 创建纹理
        const texture = device.createTexture({
            size: [bitmap.width, bitmap.height],
            format: "rgba8unorm",
            usage:
                GPUTextureUsage.TEXTURE_BINDING |
                GPUTextureUsage.COPY_DST |
                GPUTextureUsage.RENDER_ATTACHMENT,
        })

        // 复制ImageBitmap到纹理
        device.queue.copyExternalImageToTexture(
            { source: bitmap },
            { texture: texture },
            { width: bitmap.width, height: bitmap.height }
        )

        // 创建绑定组
        const bindGroup = device.createBindGroup({
            layout: pipeline.getBindGroupLayout(0),
            entries: [
                { binding: 0, resource: sampler },
                { binding: 1, resource: texture.createView() },
            ],
        })

        // 缓存纹理和绑定组
        const textureData = {
            texture,
            bindGroup,
            width: bitmap.width,
            height: bitmap.height,
        }
        textureCache.set(imageUrl, textureData)

        // 清理不再需要的位图
        bitmap.close()

        return textureData
    }

    // 渲染函数
    function renderTexture(textureData) {
        // 计算宽高比
        const canvasRatio = canvas.width / canvas.height
        const imageRatio = textureData.width / textureData.height

        // 创建命令编码器
        const commandEncoder = device.createCommandEncoder({
            label: "Image Render Encoder",
        })

        // 开始渲染通道
        const passEncoder = commandEncoder.beginRenderPass({
            colorAttachments: [
                {
                    view: context.getCurrentTexture().createView(),
                    loadOp: "clear",
                    clearValue: [0, 0, 0, 1],
                    storeOp: "store",
                },
            ],
        })

        // 设置渲染管线和绑定组
        passEncoder.setPipeline(pipeline)
        passEncoder.setBindGroup(0, textureData.bindGroup)

        // 绘制6个顶点（2个三角形）
        passEncoder.draw(6)
        passEncoder.end()

        // 提交命令
        device.queue.submit([commandEncoder.finish()])
    }

    // 资源管理函数
    function cleanupUnusedTextures(keepUrls = []) {
        const urlsToKeep = new Set(keepUrls)

        for (const [url, textureData] of textureCache.entries()) {
            if (!urlsToKeep.has(url)) {
                textureData.texture.destroy()
                textureCache.delete(url)
            }
        }
    }

    // 返回API
    return {
        async renderImage(imageUrl) {
            const textureData = await loadImageTexture(imageUrl)
            renderTexture(textureData)
            return textureData
        },

        async preloadImage(imageUrl) {
            return await loadImageTexture(imageUrl)
        },

        cleanupUnusedTextures,

        // 销毁所有资源
        destroy() {
            for (const { texture } of textureCache.values()) {
                texture.destroy()
            }
            textureCache.clear()
            // 不需要显式销毁device，但可以关闭上下文
            context.unconfigure()
        },
    }
}
